<?php

namespace app\queue\redis\in_page;

use app\exception\ApiException;
use app\extensions\lib\FcmAccessToken;
use app\extensions\lib\push\AndroidPush;
use app\extensions\lib\push\BasePush;
use app\extensions\lib\push\HmsPush;
use app\extensions\lib\push\IosPush;
use app\extensions\lib\push\Push;
use app\model\TokenInfo;
use support\Db;
use support\Log;
use Webman\RedisQueue\Consumer;
use Webman\RedisQueue\Redis;
class InPush implements Consumer
{
    // 要消费的队列名
    public $queue = 'in_udid_token_push_queue';
    public static $update_redis_queue_key = 'in_udid_token_push_list';
    public $connection = 'default';

    public static function getUrlList($uid_url,$return_sum=false){
        ini_set('memory_limit', '-1');
        $opts = ['http' => ['method' => 'GET','timeout' => 120]];
        $context = stream_context_create($opts);
        $uid_url = str_replace('https','http',$uid_url);

        $udids = array_filter(explode("\n",trim(str_replace("\r",'',file_get_contents($uid_url, false, $context)))));

        $sum = count($udids);//总数量
        if($return_sum) return $sum;
        return [$sum,$udids];
    }

    /**
     * 获取分页后的第一批 用户，其他放缓存
     * @param $request_id
     * @param $uid_url
     * @param $key
     * @return mixed|string
     */
    public static function getUidByUrl($request_id,$uid_url,$key){
        ini_set('memory_limit', '-1');
        $in_limit = 2000;
        Log::channel('request')->info($request_id."uid_url:$key:$uid_url");
        $return = '';
        try{
            list($sum,$udids) = self::getUrlList($uid_url);
            if(empty($key)) return $udids;
            $lists = array_chunk($udids,$in_limit);
            Log::channel('request')->info($request_id.'uid_url:sum-count:'.$sum);

            foreach ($lists as $k=> $list){
                $list = array_filter($list);
                $one = implode(',',$list);
                if($return){
                    \support\Redis::lPush($key,$one);//数据先放到指定缓存队列中,getUserList查询in时间久
                }else{
                    $return = $one;
                    continue;
                }

            }
        }catch (\Throwable $e){
            Log::channel('request')->warning($request_id.":getUidByUrl:".$e->getMessage());
        }


        return $return;
    }


    // 消费
    public function consume($data)
    {
        $request_id = $data['request_id'] ?? '';
        $info = $data['info'] ?? '';
        $key = $data['key'] ?? self::$update_redis_queue_key;
        $url = $data['url'] ?? '';
        $page = $data['page'] ?? 1;
        $userData = $data['userData'] ?? [];
        $channel = $userData['channel'] ?? '';
        if($url){
            $inList = $this->getUidByUrl($request_id,$url,$key);
            $data['url'] = '';//第一次设置好队列 就清除方式
        }else{
            $inList = \support\Redis::rPop($key);
        }


        $recall = false;
        if(BasePush::isRequestRecall($request_id)){
            $recall = true;
        }


        if(empty($inList) || $recall){
            //不能标识为完成，因为异步队列不一定完成。继续推送一条空的数据在队列(队列是同步的
            $status = Redis::send(\app\queue\redis\push\Push::$update_redis_queue_key,
                ['request_id'=>$request_id,'cate_id'=>$userData['cate_id'] ?? 0,'is_finish'=>true,'channel'=>$channel],1);
            \support\Redis::del($key);
            return $status;
        }

        $field = $data['field'] ?? '';
        //渠道判断
        if(in_array($channel,Push::PUSH_UDID_URL)){
            $field == 'udid' && Push::saveUidUrl($request_id, $inList);//记录推送的udid
        }
        $inList = array_filter(explode(',',$inList));
        $count = count($inList);



        unset($data['userData'][$field]);//删除动态值
        $message = $data['message'] ?? [];

        $pageInfo = $info."-inPush:page:$page";

        if(!$field){
            Log::channel('request')->warning($request_id.":count:$count:in_push:no field:in_push:$key:".json_encode($data));
            return;
        }

        $TokenInfo = new TokenInfo();
        $PublicPush = new \app\extensions\lib\push\Push();
        if($field=='token'){
            //token 没有索引
            $os_id = $userData['os_id'] ?? '';
            if(!$os_id){
                Log::channel('request')->warning($request_id.":count:$count:in_push:$key:page:$page:os_id is $os_id".json_encode($data));
            }
            $userList = $TokenInfo->getUserList($userData,1,0,$inList,$os_id);
        }else{
            $userData[$field] = $inList;
            $userList = $TokenInfo->getUserList($userData);
            $fieldLists = [];
            foreach ($userList as $os_id => $items){
                foreach ($items as $package_id => $item){
                    $fieldLists[$os_id][$package_id] = count(explode(',',$item['udids']));
                }
            }
            Log::channel('request')->info($request_id.":count:$count:in_push:$key:page:$page".json_encode($data).'::'.json_encode($fieldLists));

        }
        $results = $PublicPush->push($userList,$message,true,$request_id,[],$pageInfo);
        Log::channel('request')->info($request_id.":count:$count:in_push:$key:page:$page".json_encode($data).'::'.json_encode($results));

        //继续队列(继续消费
        $page++;
        $data['page'] = $page;
        Redis::send($this->queue,$data);

    }

}
